package com.serverTechnology.teamsGroups.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.sys.modular.user.service.SysUserOrgService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.serverTechnology.teamsGroups.Enum.TeamsGroupEnum;
import com.serverTechnology.teamsGroups.entity.dto.GroupUserDto;
import com.serverTechnology.teamsGroups.entity.dto.TeamsGroupAddDto;
import com.serverTechnology.teamsGroups.entity.dto.TeamsGroupEditDto;
import com.serverTechnology.teamsGroups.entity.GroupUser;
import com.serverTechnology.teamsGroups.mapper.GroupUserMapper;
import com.serverTechnology.teamsGroups.service.IGroupUserService;
import com.serverTechnology.teamsGroups.entity.vo.TeamsGroupAddVo;
import com.serverTechnology.teamsGroups.entity.TeamsGroup;
import com.serverTechnology.teamsGroups.mapper.TeamsGroupMapper;
import com.serverTechnology.teamsGroups.service.ITeamsGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.serverTechnology.teamsGroups.entity.dto.TeamsGroupDto;
import com.serverTechnology.teamsGroups.entity.vo.TeamsGroupDetailsVo;
import com.serverTechnology.teamsGroups.entity.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * <p>
 * 班组表 服务实现类
 * </p>
 *
 * @author 王凯炫
 * @since 2024-07-28
 */
@Service("TeamsGroupServiceImpl")
public class TeamsGroupServiceImpl extends ServiceImpl<TeamsGroupMapper, TeamsGroup> implements ITeamsGroupService {
    @Autowired
    private TeamsGroupMapper teamsGroupMapper;

    @Resource(name = "GroupUserServiceImpl")
    private IGroupUserService iGroupUserService;
    @Autowired
    private GroupUserMapper groupUserMapper;
    @Resource
    private SysUserOrgService sysUser0rgService;

    /**
     * 查询人员
     *
     * @return
     */
    @Override
    public PageResult<UserVo> selectuser() {

        List<GroupUser> list = iGroupUserService.list();

        // 获取已选择的用户ID
        Set<BigDecimal> collect = list.stream().map(GroupUser::getUserId).collect(Collectors.toSet());

        return getUserVoPageResult(collect);
    }

    /**
     * 查询详情
     *
     * @param id
     * @return
     */
    @Override
    public TeamsGroupDetailsVo sele(Long id) {
        TeamsGroup one = this.getOne(new LambdaUpdateWrapper<TeamsGroup>().eq(TeamsGroup::getId, id));

        // 调试输出
        System.out.println("Details: " + one);

        TeamsGroupDetailsVo teamsGroupDetailsVo = new TeamsGroupDetailsVo();
        BeanUtil.copyProperties(one, teamsGroupDetailsVo);
        return teamsGroupDetailsVo;
    }


    /**
     * 获取用户信息
     * @param collect
     * @return
     */
    private PageResult<UserVo> getUserVoPageResult(Set<BigDecimal> collect) {
        Page<UserVo> sysUservoPage = teamsGroupMapper.selectTeamUser(PageFactory.defaultPage());
        // 过滤掉已选择的用户
        if(ObjectUtil.isEmpty(collect)){
            List<UserVo> collected = sysUservoPage.getRecords().stream().filter(record -> !collect.contains(record.getUserId()))
                    .collect(Collectors.toList());
            // 过滤掉已选择的用户
            sysUservoPage.setRecords(collected);
        }

        //遍历查询结果，增加对用户部门信息的返回
        for (UserVo record : sysUservoPage.getRecords()) {
            record.setUserOrgDTO(sysUser0rgService.getUserMainOrgInfo(record.getUserId()));
            record.setUserIdStr(record.getUserId().toString());
        }

        return PageResultFactory.createPageResult(sysUservoPage);
    }


    /**
     * 添加班组
     * @param teamsGroup 请求参数
     */
    @Override
    @Transactional
    public void add(TeamsGroupAddDto teamsGroup) {
        // 将dto转换为实体
        TeamsGroup teamsGroup1 = new TeamsGroup();
        BeanUtil.copyProperties(teamsGroup, teamsGroup1);
        try {
            this.save(teamsGroup1);
        } catch (Exception e) {
            throw new RuntimeException("班组编码重复");
        }
        if (ObjectUtil.isNotEmpty(teamsGroup.getGroupUserDtoList())) {
            addUser(teamsGroup, teamsGroup1.getId());
        }
    }

    /**
     * 添加班组人员
     */
    public void addUser(TeamsGroupAddDto teamsGroup, Long groupId) {
        List<GroupUser> groupUsers = new ArrayList<>();

        /**
         * 遍历dto集合
         */
        for (GroupUserDto groupUserDto : teamsGroup.getGroupUserDtoList()) {
            GroupUser groupUser = new GroupUser(); // 在循环中实例化新的 GroupUser 对象
            groupUser.setId(IdWorker.getId()); // 使用 MyBatis-Plus 生成唯一 ID
            groupUser.setGroupId(groupId);
            groupUser.setUserId(groupUserDto.getUserId());
            groupUsers.add(groupUser);
        }

        iGroupUserService.saveBatch(groupUsers);
    }

    @Override
    public void editMonitor(GroupUserDto groupUserDto) {
        LambdaUpdateWrapper<GroupUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(GroupUser::getGroupId, groupUserDto.getGroupId())
                .eq(GroupUser::getMonitor, TeamsGroupEnum.MONITOR.getValue());
        // 获取同一组中当前的班长
        GroupUser one = groupUserMapper.selectOne(wrapper);

        // 判断是否已经有班长
        if (ObjectUtil.isNotEmpty(one) && !one.getUserId().equals(groupUserDto.getUserId())) {
            throw new RuntimeException("只能设置一个班长");
        }

        // 更新指定用户为班长
        boolean updateResult = iGroupUserService.update(
                new LambdaUpdateWrapper<GroupUser>()
                        .eq(GroupUser::getUserId, groupUserDto.getUserId())
                        .set(GroupUser::getMonitor, groupUserDto.getMonitor())
        );


    }


    /**
     * 删除班组人员
     * @param id 请求参数
     */
    @Override
    public void del(Long id) {
        this.removeById(id);
    }

    /**
     * 编辑班组表
     * @param teamsGroup 请求参数
     */
    @Override
    public void edit(TeamsGroupEditDto teamsGroup) {
        TeamsGroup teamsGroup1 = new TeamsGroup();
        BeanUtil.copyProperties(teamsGroup, teamsGroup1);
        try {
            this.updateById(teamsGroup1);
        }catch (Exception e){
            throw new RuntimeException("班组编码重复");
        }
    }

    /**
     * 查询班组详情
     * @param teamsGroup 请求参数
     * @return
     */
    @Override
    public TeamsGroup detail(TeamsGroup teamsGroup) {
        return this.getById(teamsGroup);
    }

    /**
     * 分页查询班组表列表
     *
     * @param teamsGroup 请求参数
     * @return
     */
    @Override
    public Page<TeamsGroupAddVo> findPage(TeamsGroupDto teamsGroup) throws ParseException {
        // 解析和验证日期时间
        String startDate = teamsGroup.getStartDate();
        String endDate = teamsGroup.getEndDate();
        MPJLambdaWrapper<TeamsGroup> wrapper = new MPJLambdaWrapper<>();
        Date end = DateUtil.parse(endDate);
        Date start = DateUtil.parse(startDate);
        // 构建查询条件
        wrapper.selectAll(TeamsGroup.class)
                .eq(ObjectUtil.isNotEmpty(teamsGroup.getLine()), TeamsGroup::getLine, teamsGroup.getLine())
                .eq(ObjectUtil.isNotEmpty(teamsGroup.getOutsideGroup()), TeamsGroup::getOutsideGroup, teamsGroup.getOutsideGroup())
                .like(ObjectUtil.isNotEmpty(teamsGroup.getGroupName()), TeamsGroup::getGroupName, teamsGroup.getGroupName())
                .eq(ObjectUtil.isNotEmpty(teamsGroup.getWorkId()), TeamsGroup::getWorkId, teamsGroup.getWorkId())
                .eq(ObjectUtil.isNotEmpty(teamsGroup.getGroupStatus()), TeamsGroup::getGroupStatus, teamsGroup.getGroupStatus())
                .between(ObjectUtil.isNotEmpty(startDate) && ObjectUtil.isNotEmpty(endDate), TeamsGroup::getCreateTime,
                        start , end);

        // 执行查询
        Page<TeamsGroupAddVo> teamsGroupDtoPage = teamsGroupMapper.selectJoinPage(PageFactory.defaultPage(), TeamsGroupAddVo.class, wrapper);
        return teamsGroupDtoPage;
    }
}
